#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#2011/7/4 修改发短信方式，通过往139邮箱发邮件来触发短信，google日历插入事件的方式发短信不好用了。
#用cn13699811778@gmail.com 来发邮件到139邮箱
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
import logging
from google.appengine.ext import webapp
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import mail
import cgi
import wsgiref.handlers
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.api import urlfetch
import urllib # Used to unescape URL parameters.
#import settings

try:
  from xml.etree import ElementTree
except ImportError:
  from elementtree import ElementTree
import gdata.calendar.service#Google data calender
import gdata.service
import atom.service
import gdata.calendar
import atom
import getopt
import sys
import string
import time
from google.appengine.api import mail

class CalendarExample:
  def __init__(self):
    self.cal_client = gdata.calendar.service.CalendarService()
    self.cal_client.email = 'papapadpad@gmail.com'
    self.cal_client.password = 'papadada'
    self.cal_client.source = 'papapadpad@gmail.com'
    self.cal_client.ProgrammaticLogin()
  def _InsertEvent(self, title='new email',start_time=None, end_time=None, recurrence_data=None,reminder_minutes=9):
    feed = self.cal_client.GetOwnCalendarsFeed()#
    calURI=None
    for i,a_calendar in zip(xrange(len(feed.entry)), feed.entry):
      if(a_calendar.title.text=="papapadpad@gmail.com"):
        calURI=a_calendar.id.text[63:]
        break
    if(calURI==None):
        calURI=self._InsertCalendar().id.text[63:]
    calURI='/calendar/feeds/'+calURI+'/private/full'
    event = gdata.calendar.CalendarEventEntry()
    event.title = atom.Title(text=title)
#    event.content = atom.Content(text=content)
#    event.where.append(gdata.calendar.Where(value_string=where))
##########################################


#    event.content = atom.Content(text='test')
    start_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime(time.time() + 70+60*5))
    end_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z',time.gmtime(time.time() + 6000))
    event.when.append(gdata.calendar.When(start_time=start_time, end_time=end_time))
    event.where.append(gdata.calendar.Where(value_string='fromxsms'))
#    event.when.append(gdata.calendar.When(start_time=start_time))
    reminder=gdata.calendar.Reminder(minutes=1, method='sms')
    event.when[0].reminder.append(reminder)

    new_event = self.cal_client.InsertEvent(event, 'http://www.google.com/calendar/feeds/default/private/full')

    return new_event
  def _InsertCalendar(self, title='papapadpad@gmail.com',
      description='This is a calendar contains your sms',
      time_zone='Asia/Shanghai', hidden=False, location='papapadpad@gmail.com',
      color='#2952A3'): 
    calendar = gdata.calendar.CalendarListEntry()
    calendar.title = atom.Title(text=title)
    calendar.summary = atom.Summary(text=description)
    calendar.where = gdata.calendar.Where(value_string=location)
    calendar.color = gdata.calendar.Color(value=color)
    calendar.timezone = gdata.calendar.Timezone(value=time_zone)
    if hidden:
      calendar.hidden = gdata.calendar.Hidden(value='true')
    else:
      calendar.hidden = gdata.calendar.Hidden(value='false')
    new_calendar = self.cal_client.InsertCalendar(new_calendar=calendar)
    return new_calendar

class XSMS(webapp.RequestHandler):#发短信的类，处理发短信接口
    def get(self):
        xsms=self.request.get('xsms')
        if len(xsms)>0:
            self.response.out.write('send xsms=' + xsms)
            self.sendsms(xsms)
        self.response.out.write("""
          <form action="/xsms" method="get">
            <div><textarea name="xsms" rows="3" cols="60"></textarea></div>
            <div><input type="submit" value="Send sms to me"></div>
          </form>
        </body>""")
    def sendsms(self,smstext):
#        self.touchGG(smstext)
#        sms=CalendarExample()
#        sms._InsertEvent(title=smstext,reminder_minutes=1)
        self.send139mail(smstext)
        
    def send139mail(self,mtitle,mbody='nobody'):
        mail.send_mail(sender="cn13699811778@gmail.com",
                      to="13699811778@139.com",
                      subject=mtitle,
                      body=mbody)


def main():
    application = webapp.WSGIApplication([('/xsms',XSMS)],
                                         debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
